package com.cred.industries.core.util;

import java.util.concurrent.locks.ReadWriteLock;

public class ReadWriteAutoLock implements AutoCloseable {

	static public ReadWriteAutoLock readLock(ReadWriteLock readLock) {
	
		return new ReadWriteAutoLock(readLock, true);
	}
	
	static public ReadWriteAutoLock writeLock(ReadWriteLock writeLock) {
		
		return new ReadWriteAutoLock(writeLock, false);
	}
	
	private ReadWriteLock mReadWriteLock;
	private boolean mIsReadOnly = false;
	
	private ReadWriteAutoLock(ReadWriteLock readWriteLock, boolean isReadOnly) {
		mReadWriteLock = readWriteLock;
		mIsReadOnly = isReadOnly;
		if(mIsReadOnly) {
			mReadWriteLock.readLock().lock();
		} else {
			mReadWriteLock.writeLock().lock();
		}
	}
	
	@Override
	public void close() {

		if(mIsReadOnly) {
			mReadWriteLock.readLock().unlock();
		} else {
			mReadWriteLock.writeLock().unlock();
		}
	}

}
